package com.yst.gateway.monitor.common.utils;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.yst.gateway.monitor.models.SysMenus;
import com.yst.gateway.monitor.models.SysUsers;

/**
 * 当前用户缓存信息
 * @author sheungxin
 *
 */
public class LoginUserCache {
	
	/**
	 * 获取登录用户编号
	 * @return
	 */
	public static String getUserId(){
		SysUsers sysUser=getUser();
		return sysUser==null?"":sysUser.getSysUserId();
	}

	/**
	 * 获取登录的用户信息
	 * @return
	 */
	public static SysUsers getUser(){
		SysUsers sysUser=null;
		if(getRequest().getSession().getAttribute("MONITOR_USER")!=null){
			sysUser=((SysUsers)getRequest().getSession().getAttribute("MONITOR_USER"));
		}
		return sysUser;
	}
	
	/**
	 * 缓存当前用户的菜单信息
	 * @param menuList
	 * @throws JsonProcessingException
	 */
	public static void cacheUserMenus(List<SysMenus> menuList) throws JsonProcessingException{
		if(menuList!=null&&menuList.size()>0){
			getRequest().getSession().setAttribute("MONITOR_MENUS", JsonUtils.format(menuList));
		}
	}
	
	/**
	 * 缓存当前用户的基础信息
	 * @param sysUser
	 */
	public static void cacheUserInfo(SysUsers sysUser){
		if(sysUser!=null){
			getRequest().getSession().setAttribute("MONITOR_USER", sysUser);
		}
	}
	
	/**
	 * 获取当前的request的对象
	 * @return
	 */
	public static HttpServletRequest getRequest(){
		return ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();		
	}
	
	/**
	 * 注销当前session
	 */
	public static void invalidUser(){
		getRequest().getSession().invalidate();
	}
}
